<template>
  <m-form ref="MForm" class="mForm" :model="formData">
    <m-form-item
      label="上传文件"
      prop="extractFilename"
      :rules="[{ required: true, message: '请上传文件' }]"
    >
      <el-upload
        ref="upload"
        :multiple="false"
        :show-file-list="true"
        :file-list="upload.fileList"
        :action="upload.action"
        :data="upload.data"
        :before-upload="handleBeforeUpload"
        :on-success="handleUploadSuccess"
        :on-preview="handleOnPreview"
        :on-remove="handleOnRemove"
        :on-error="handleOnError"
        :on-change="handleChange"
      >
        <m-button>选择文件</m-button>
      </el-upload>
    </m-form-item>
    <m-form-item
      label="文件类型"
      prop="fileType"
      :rules="[{ required: true, message: '文件类型' }]"
    >
      <m-select v-model="formData.fileType" placeholder="文件类型">
        <m-option
          v-for="item in fileTypeData"
          :key="item.dictValue"
          :label="item.dictLabel"
          :value="item.dictValue"
        >
        </m-option>
      </m-select>
    </m-form-item>
    <m-form-item
      label="文件名称"
      prop="fileName"
      :rules="[{ required: true, message: '文件名称' }]"
    >
      <m-input maxlength="50" v-model.trim="formData.fileName"> </m-input>
    </m-form-item>
    <m-form-item>
      <m-button
        type="primary"
        :disabled="
          !formData.extractFilename || formData.extractFilename == null
        "
        @click="saveForm"
        >保存</m-button
      >
      <m-button @click="closeFun">取消</m-button>
    </m-form-item>
  </m-form>
</template>

<script>
import $config from "@/config";
import { getDict } from "@/request/common";
import { fileAdd, fileEdit, fileDetail } from "@/request/file/List";
export default {
  name: "fileAdd",
  data() {
    return {
      upload: {
        fileList: [],
        action: $config.path + "/file/upload",
        data: {
          module: "CloudMiddleBusiness/ChargeFinance",
        },
      },
      fileTypeData: [],
      formData: {
        fileName: null,
        fileType: null,
        extractFilename: null,
      },
    };
  },
  model: {},
  props: ["fileKey", "deviceKey"],
  components: {},
  watch: {
    fileKey: {
      handler(e) {
        if (e) {
          this.getFileFun(e);
        }
      },
    },
  },
  computed: {},
  mounted() {
    // 获取文件类型
    getDict("file_type").then((res) => {
      this.fileTypeData = res.data.data;
    });
  },

  methods: {
    getFileTypeByExt(filename) {
      var ext = filename.split(".").pop().toLowerCase(); //获取文件后缀名
      var imageExts = ["jpg", "jpeg", "png", "gif", "bmp", "tiff", "svg"];
      var audioExts = ["mp3", "wav", "aac", "flac", "ogg", "m4a"];
      var videoExts = ["mp4", "avi", "mkv", "wmv", "mov", "mpeg", "webm"];

      if (imageExts.includes(ext)) {
        this.formData.fileType = "image";
        return "image"; //图片
      } else if (audioExts.includes(ext)) {
        this.formData.fileType = "audio";
        return "audio"; //音频
      } else if (videoExts.includes(ext)) {
        this.formData.fileType = "video";
        return "video"; //视频
      } else {
        return "unknown"; //未知类型
      }
    },
    // 上传前处理
    handleBeforeUpload(file) {
      this.handleOnRemove();
      if (this.getFileTypeByExt(file.name) == "unknown") {
        this.$message.error("上传文件格式错误，仅持图片、视频、音频");
        this.upload.fileList = [];
        return false;
      } else {
        let isRightSize = file.size / 1024 / 1024 < 500;
        if (!isRightSize) {
          this.$message.error("上传文件大小不能超过500MB，请重新上传");
          this.upload.fileList = [];
        }
        return isRightSize;
      }
    },
    handleChange(file, fileList) {
      this.upload.fileList = fileList.slice(-1);
    },
    // 上传成功回调
    handleUploadSuccess(res, file, fileList) {
      if (res.code === 200) {
        this.$message.success("上传成功");
        this.upload.fileList = fileList[fileList.length - 1];
        this.formData.extractFilename =
          fileList[fileList.length - 1].response.data.extractFilename;
        this.formData.fileName = fileList[fileList.length - 1].name;
      } else {
        this.$message.error("上传失败");
      }
    },
    handleOnError() {
      this.$message.error("上传失败");
    },
    // 上传文件预览
    handleOnPreview(file) {
      this.downloadFile(file.url, file.name);
    },
    // 上传文件删除
    handleOnRemove(file, fileList) {
      this.formData.extractFilename = null;
      this.formData.fileName = null;
      this.formData.fileType = null;
      this.$refs.upload.clearFiles();
    },
    // 编辑详情
    getFileFun(fileKey) {
      fileDetail(fileKey)
        .then((res) => {
          console.log(res);
          if (res.data.code == 200) {
            let resData = res.data.data;
            this.formData = {
              fileName: resData.fileName,
              fileType: resData.fileType,
              extractFilename: resData.extractFilename,
            };
            this.upload.fileList = [
              {
                name: resData.fileName,
                url: resData.url,
              },
            ];
            console.log(this.upload.fileList);
          }
        })
        .catch((err) => {});
    },
    saveForm() {
      this.$refs["MForm"].validate((valid) => {
        if (valid) {
          if (!this.$route.query.fileKey) {
            const params = {
              fileName: this.formData.fileName,
              fileType: this.formData.fileType,
              extractFilename: this.formData.extractFilename,
              deviceKey: this.deviceKey,
            };
            fileAdd(params)
              .then((res) => {
                this.$m.message("新增成功", "success", {
                  onClose: () => {},
                });
                if (this.deviceKey) {
                  this.$emit("updeData");
                } else {
                  this.$m.back();
                }
              })
              .catch((err) => {});
          } else {
            this.formData.fileKey = this.fileKey;
            fileEdit(this.formData).then((res) => {
              this.$m.message("编辑成功", "success", {
                onClose: () => {},
              });
              this.$m.back();
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    closeFun() {
      if (this.deviceKey) {
        this.$emit("updeData");
      } else {
        this.$m.back();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/MUI/style/var.scss";
</style>
